<?php


namespace api\zmt\controller;


use api\zmt\model\UserModel;
use cmf\controller\RestBaseController;
use think\Exception;
use think\facade\Db;
use think\Request;


class MoneyLogController extends RestBaseController
{
    public function add(Request $request){
        //接受money
        $money = input('money/f','');
        //验证
        if (empty($money)||$money <=0 ){
            $this->error('充值格式不符合');
        }
        $user = UserModel::find($request->userId);
        if(!$user){
            $this->error('账号异常');
        }
        $after = $user['wallet'] + $money;

        //开启事务
        Db::startTrans();
        //作用域
        $addLog = false;
        $log = false;
        try {
            //添加流水记录
            $addLog = add_money_log($request->userId,$money,'充值余额',$user['wallet'],$after,'1');
            //添加用户余额
            $log = UserModel::where('id',$request->userId)->update(['wallet' => $after]);
        }catch (Exception $exception){
            Db::rollback();
            $this->error('充值失败');
        }

//        $user->wallet = $user->wallet + $money;
        if($log && $addLog){
            //提交事务
            Db::commit();
            $this->success('充值成功');
        }else{
            //回滚事务
            Db::rollback();
            $this->error('充值失败');
        }

    }
}